package com.cicoding.tcp.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class NettyClient {
    private final String host;
    private final int port;
    private Channel channel;
    private EventLoopGroup group;

    public NettyClient(String host, int port) {
        this.host = host; // ip
        this.port = port; // port
    }

    public void start() throws Exception {
        group = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyClientHandler());
                        }
                    });

            ChannelFuture f = b.connect(host, port).sync();
            System.out.println("Connected to " + host + ":" + port);
            channel = f.channel();

            System.out.println("通道是否正常" + channel.isActive());
//            f.channel().closeFuture().sync();
        } finally {
//            group.shutdownGracefully();
        }

    }

    /*
     * 功能描述: 检查通道是否 连接中
     * @param
     * @Return: java.lang.Boolean
     * @Author: 努阳
     * @Date: 2024/6/6 10:31
     */
    public Boolean checkChannelActive() {
        if (channel != null && channel.isActive()){
            return  true;
        };
        //重新初始化通道
        try {
            start();
        } catch (Exception e) {
            log.error("重新初始化通道失败");
            throw new RuntimeException(e);
        }

        return false;
    }

    public void shutdown() {
        if (channel != null) {
            // 关闭Channel
            channel.close();
        }

        if (group != null) {
            // 关闭EventLoopGroup
            group.shutdownGracefully();
        }
    }


    public Boolean sendMessage(String message) {
        System.out.println("发送消息："+ message);
        if (channel != null && channel.isActive()) {
            try {
                channel.writeAndFlush(Unpooled.copiedBuffer(message + "$", CharsetUtil.UTF_8)).sync();
            } catch (InterruptedException e) {
                System.out.println("发送失败--出现异常");
                e.printStackTrace();
                return false;
            }
            return true;
        }
        return false;
    }

}
